package com.zerosky.crm.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zerosky.crm.po.Customer;
import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.Invite;
import com.zerosky.crm.service.CustomerService;
import com.zerosky.crm.service.EmployeeService;
import com.zerosky.crm.service.InviteService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.PageInfo;

/**
 * 邀约功能的Controller
 * 
 * @author 周正祥
 *
 */
@Controller
public class InviteController extends BaseAction {
	private Logger logger = LoggerFactory.getLogger(InviteController.class); // 日志

	@Resource(name = "inviteService")
	private InviteService inviteService;

	@Resource(name = "customerService")
	private CustomerService customerService;

	@Resource(name = "employeeService")
	private EmployeeService employeeService;

	private int count = 0;// 用于统计

	/**
	 * 获取邀约列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/inviteList.do")
	@ResponseBody
	public Map<String, Object> TrainList(HttpServletRequest request, HttpSession session, HttpServletResponse response,
			Integer limit, Integer page, String inviteName, Integer activityId,String section) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Map<String, Object> param = new HashMap<String, Object>();// 定义条件集合
		try {
			param.put("page", page);
			param.put("pageSize", limit);
			if (Strings.isNotEmpty(inviteName)) {
				param.put("inviteName", inviteName);
			}
			if (Strings.isNotEmpty(section)) {
				if(!section.equals("all")){
					param.put("section", section);
				}
			}else{
				param.put("notSection", "-1");
			}
			param.put("activityId", activityId);
			PageInfo<Invite> pageRole = inviteService.getInviteList(param);
			//Invite invite = inviteService.getStatisticalMagnitude(activityId);
			//json.put("invite", invite);
			json.put("total", pageRole.getPageCount());
			json.put("data", pageRole.getList());
			json.put("code", "0");
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", "-1");
		}
		return json;

	}

	/**
	 * 获取客户列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/inviteCustomerList.do")
	@ResponseBody
	public Map<String, Object> customerList(HttpServletRequest request, HttpSession session,
			HttpServletResponse response, Integer limit, Integer page, String customerName, String activityId)
			throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户信息
		Map<String, Object> param = new HashMap<String, Object>();// 定义条件集合
		Map<String, Object> map = new HashMap<String, Object>();// 定义条件集合
		PageInfo<Customer> pageInfo = new PageInfo<Customer>();
		try {
			pageInfo.setPageNo(page);
			pageInfo.setPageSize(limit);
			if (Strings.isNotEmpty(customerName)) {
				param.put("customerName", customerName);
			}
			//param.put("departmentId", user.getDept().getDeptId());//获取自己所在的部门ID
			// map.put("departmentId", user.getDept().getDeptId());
			map.put("activityId", activityId);
			PageInfo<Customer> pageRole = customerService.getCustomerPageInfoList(param, pageInfo);
			PageInfo<Invite> list = inviteService.getInviteList(map);
			List<Customer> list1 = checkCustomer(pageRole, list);
			json.put("count", count);
			json.put("total", pageRole.getPageCount());
			json.put("data", list1);
			json.put("code", "0");
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", "-1");
		}
		return json;

	}

	/**
	 * 添加邀约记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertInvite.do")
	@ResponseBody
	public Map<String, Object> insertVisit(Invite invite, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			String StrId = UUID.randomUUID().toString();
			Employee user = (Employee) session.getAttribute("loginUser");// 获取员工
			Customer customer = (Customer) session.getAttribute("loginCustomer");// 获取登录客户
			invite.setInviteId(StrId);
			invite.setCreateDate(new Date());
			invite.setCreatePeople(user.getEmployeeId());
			// invite.setCustomerType("0");
			invite.setStatus("0");
			invite.setSection("-1");// 0、预约，1、签到，2、邀约
			inviteService.saveInvite(invite, "新增");
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}
	
	
	/**
	 * 添加邀约记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertInviteCode.do")
	@ResponseBody
	public Map<String, Object> insertInviteCode(Invite invite, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			String StrId = UUID.randomUUID().toString();
			
			
			Employee user = employeeService.getEmployeeById(request.getParameter("empId"));
			Customer customer = (Customer) session.getAttribute("loginCustomer");// 获取登录客户
			
			json.put("customerId", customer.getCustomerId());
			json.put("empId", user.getEmployeeId());
			if (inviteService.getInviteList(json).getPageCount()==0) {
				//employeeService.getInviteList(json);
				
				invite.setInviteId(StrId);
				invite.setCreateDate(new Date());
				invite.setCreatePeople(user.getEmployeeId());
				invite.setCustomerId(customer.getCustomerId());
				invite.setCustomerName(customer.getCustomerName());
				// invite.setCustomerType("0");
				invite.setStatus("0");
				invite.setSection("2");// 0、邀约，1、签到 2、浏览
				
				inviteService.saveInvite(invite, "新增");
			}
			
			 
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}
	
	
	
	/**
	 * 添加邀约记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertInviteSign.do")
	@ResponseBody
	public ModelAndView insertInviteSign(Invite invite, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		
		ModelAndView m = new ModelAndView("WEB-INF/wap/success");
		Map<String, Object> json = new HashMap<String, Object>();
		
		try {
			String StrId = UUID.randomUUID().toString();
			Employee user = employeeService.getEmployeeById(request.getParameter("empId"));
			String empid2= request.getParameter("empId");
			String empid3= request.getParameter("empid");

			Customer customer = (Customer) session.getAttribute("loginCustomer");// 获取登录客户
			
			json.put("customerId", customer.getCustomerId());
			json.put("empId", user.getEmployeeId());
			if (inviteService.getInviteList(json).getPageCount()==0) {
				invite.setInviteId(StrId);
				invite.setCreateDate(new Date());
				invite.setCreatePeople(user.getEmployeeId());
				invite.setCustomerId(customer.getCustomerId());
				invite.setCustomerName(customer.getCustomerName());
				// invite.setCustomerType("0");
				invite.setStatus("0");
				//invite.setSection("2");// 0、邀约，1、签到 2、浏览 3、分享记录。
				inviteService.saveInvite(invite, "新增");
				switch (invite.getSection()) {
				case "0":
					m.addObject("msg", "预约成功!");
					break;
				case "1":
					m.addObject("msg", "签到成功!");
					break;
				default:
					break;
				}
			}else
			{
				m = new ModelAndView("WEB-INF/wap/error");
				m.addObject("msg","请勿重复操作!");
			}
			 
		} catch (Exception e) {
			m = new ModelAndView("WEB-INF/wap/error");
			m.addObject("msg","获取数据失败，原因："+e.getMessage());
			logger.error("获取数据失败，原因：" + e);
		}
		return m;
	}
	
	
	

	/**
	 * 添加签到记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertInviteRegister.do")
	@ResponseBody
	public Map<String, Object> insertInviteRegister(Invite invite, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			String StrId = UUID.randomUUID().toString();
			Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户
			Customer customer = (Customer) session.getAttribute("loginCustomer");// 获取登录客户
			invite.setInviteId(StrId);
			//invite.setCreateDate(new Date()); //自定义添加数据
			//invite.setCreatePeople(user.getName());
			// invite.setCustomerType("0");
			invite.setStatus("0");
			invite.setSection("1");// 0、邀约，1、签到
			inviteService.saveInvite(invite, "新增");
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}
	
	
	

	/**
	 * 批量新增邀约记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertCustomerInvite.do")
	@ResponseBody
	public Map<String, Object> insertCustomerInvite(String customerText, Integer activityId, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户
			String[] customerId = customerText.split(",");
			for (int i = 0; i < customerId.length; i++) {
				String StrId = UUID.randomUUID().toString();
				Invite invite = new Invite();
				Customer customer = customerService.getCustomerById(customerId[i]);
				invite.setInviteId(StrId);
				invite.setActivityId(activityId);
				invite.setCustomerId(customer.getCustomerId());
				invite.setCustomerName(customer.getCustomerName());
				invite.setCreateDate(new Date());
				invite.setCreatePeople(user.getEmployeeId());
				// invite.setCustomerType("1");
				invite.setStatus("0");
				invite.setSection("-1");
				inviteService.saveInvite(invite, "新增");
			}
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 批量删除邀约记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteCustomerInvite.do")
	@ResponseBody
	public Map<String, Object> deleteCustomerInvite(String customerText,String activityId ,HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			
			map.put("activityId", activityId);
			String[] customerId = customerText.split(",");
			for (int i = 0; i < customerId.length; i++) {
				map.put("customerId", customerId[i]);
				inviteService.deleteInviteById(map);
			}
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 单独新增邀约记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertCustomerInviteToId.do")
	@ResponseBody
	public Map<String, Object> insertCustomerInviteToId(String customerId, Integer activityId,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户
			String StrId = UUID.randomUUID().toString();
			Invite invite = new Invite();
			Customer customer = customerService.getCustomerById(customerId);
			invite.setInviteId(StrId);
			invite.setActivityId(activityId);
			invite.setCustomerId(customer.getCustomerId());
			invite.setCustomerName(customer.getCustomerName());
			invite.setCreateDate(new Date());
			invite.setCreatePeople(user.getEmployeeId());
			// invite.setCustomerType("1");
			invite.setStatus("0");
			invite.setSection("-1");
			inviteService.saveInvite(invite, "新增");
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 单独删除邀约记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteCustomerInviteToId.do")
	@ResponseBody
	public Map<String, Object> deleteCustomerInviteToId(String customerId,String activityId, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("customerId", customerId);
			map.put("activityId", activityId);
			inviteService.deleteInviteById(map);
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	public List<Customer> checkCustomer(PageInfo<Customer> page1, PageInfo<Invite> page2) {
		List<Customer> customerList = page1.getList();
		count = 0;
		if (page2 != null) {
			List<Invite> inviteList = page2.getList();
			for (int i = 0; i < customerList.size(); i++) {
				for (int j = 0; j < inviteList.size(); j++) {
					if (customerList.get(i).getCustomerId().equals(inviteList.get(j).getCustomerId())) {
						customerList.get(i).setIsInvite("1");
						count++;
						break;
					}
				}
			}
		}
		return customerList;
	}

}
